package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.repository.IStrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

/**
 * @author hslef
 */
@Service
public class StrategyCommentImpl implements IStrategyCommentService {
    @Autowired
    private IStrategyCommentRepository commentRepository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void addComment(StrategyComment comment) {
        comment.setCreateTime(new Date());
        commentRepository.save(comment);
    }

    @Override
    public Page<StrategyComment> query(StrategyCommentQuery qo) {
        Query query = new Query();
        if (qo.getDetailId() != null) {
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }
        long count = template.count(query, StrategyComment.class);
        if (count > 0) {
            Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1,
                    qo.getPageSize(),
                    Sort.by(Sort.Direction.DESC,"createTime")
            );
            query.with(pageable);
            List<StrategyComment> strategyComments =  template.find(query, StrategyComment.class);
            return new PageImpl<>(strategyComments,pageable,count);
        }
        return Page.empty();
    }

    @Override
    public StrategyComment commentThumbUp(String toid, Long fromid) {
        StrategyComment strategyComment = commentRepository.findById(toid).get();
        List<Long> thumbuplist = strategyComment.getThumbuplist();
        int thumbupnum = strategyComment.getThumbupnum();
        if(thumbuplist.contains(fromid)){
            thumbupnum --;
            thumbuplist.remove(fromid);

        }else {
            thumbupnum ++;
            thumbuplist.add(fromid);
        }
        strategyComment.setThumbupnum(thumbupnum);
        commentRepository.save(strategyComment);
        return strategyComment;
    }
}
